package com.yinhanshi.s3test.http;

import android.util.Log;

import com.yinhanshi.s3test.utils.LoginManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BaseApiRetrofit {
    public static final String TAG = "BaseApiRetrofit";

    private static OkHttpClient mClient;

    public static OkHttpClient getClient() {
        return mClient;
    }


    static {
        mClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(0, TimeUnit.SECONDS)
                .writeTimeout(0, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Log.d(TAG, "read:Cookie " + LoginManager.getInstance().readCookies());

                        Request request;
                        if (chain.request().url().toString().contains("calabash/file/_upload")) {
                            request = chain.request()
                                    .newBuilder()
                                    .addHeader("Cookie", LoginManager.getInstance().readCookies())
                                    .addHeader("Connection", "close")
                                    .build();
                        } else {
                            request = chain.request()
                                    .newBuilder()
                                    .addHeader("Cookie", LoginManager.getInstance().readCookies())
                                    .build();
                        }
                        Response response = chain.proceed(request);

                        return response;
                    }
                })
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        LoginManager.getInstance().saveCookies(cookies.get(0).toString());
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        return new ArrayList<>();
                    }
                })
                .build();
    }
}
